package work.shyk.kongMonitor;

import com.fasterxml.jackson.databind.JsonNode;
import utils.common.JsonUtils;
import utils.http.HttpUtil;
import work.shyk.kongMonitor.dto.param.AggsEnums;
import work.shyk.kongMonitor.dto.param.AggsTermsQuery;
import work.shyk.kongMonitor.dto.param.DefaultAggsQuery;
import work.shyk.kongMonitor.dto.param.EsAggsQuery;
import work.shyk.kongMonitor.dto.param.EsAggsQueryBuilder;
import work.shyk.kongMonitor.dto.param.FieldObj;
import work.shyk.kongMonitor.dto.param.LongValueParser;
import work.shyk.kongMonitor.dto.param.ScriptObj;
import work.shyk.kongMonitor.dto.result.EsDataResult4Service;
import work.shyk.kongMonitor.dto.result.interfaces.ValueReceiver;

import java.io.IOException;
import java.util.List;
import java.util.function.Supplier;

/**
 * description: <br>
 * createTime: 2021/3/24 15:47 <br>
 *
 * @author zzh
 */
public class Main {

    public static void main(String[] args) throws IOException {

        String esUrl = "http://10.238.219.79:9200/";
        // 构造查询条件
        EsAggsQuery build = new EsAggsQueryBuilder()
                //.addWildcardQuery("api_name.keyword", "*_*_p_*_*")
                .addRangeQuery("started_at", 1616428800000L, 1616515200000L)
                .addAggs(new AggsTermsQuery("x-service-code")
                        .addTerms("serviceCode.keyword")
                        .addAggs(new DefaultAggsQuery("outflow", AggsEnums.SUM
                                , new ScriptObj("return Long.parseLong(doc['responseSize.keyword'].value)"), new LongValueParser()))
                        .addAggs(new DefaultAggsQuery("minTimeDelay", AggsEnums.MIN
                                , new FieldObj("latencies.request")))
                        .addAggs(new DefaultAggsQuery("maxTimeDelay", AggsEnums.MAX
                            , new FieldObj("latencies.request")))
                        .addAggs(new DefaultAggsQuery("httpCode", AggsEnums.TERMS
                                , new ScriptObj("def temp = doc['responseStatus.keyword'].value;def result = temp.substring(0,1);if(result=='2') return '2';else if(result=='3')return '3'; else if(result=='4')return '4';else if(result=='5')return '5'; return 'otherCode';")) {
                            @Override
                            public ValueReceiver parse(JsonNode jsonNode, Supplier receiverSupplier) {
                                ValueReceiver valueReceiver = (ValueReceiver) receiverSupplier.get();

                                JsonNode httpCodeBucketsResult = jsonNode.get(key).get("buckets");
                                if(httpCodeBucketsResult != null) {
                                    for (JsonNode temp : httpCodeBucketsResult) {
                                        switch (temp.get("key").textValue()) {
                                            case "2":
                                                valueReceiver.receiveValue("http2xx", temp.get("doc_count").intValue());
                                                break;
                                            case "3":
                                                valueReceiver.receiveValue("http3xx", temp.get("doc_count").intValue());
                                                break;
                                            case "4":
                                                valueReceiver.receiveValue("http4xx", temp.get("doc_count").intValue());
                                                break;
                                            case "5":
                                                valueReceiver.receiveValue("http5xx", temp.get("doc_count").intValue());
                                                break;
                                            case "otherCode":
                                                valueReceiver.receiveValue("otherCode", temp.get("doc_count").intValue());
                                                break;
                                        }
                                    }
                                }
                                return valueReceiver;
                            }
                        })
                        .addAggs(new DefaultAggsQuery("inflow", AggsEnums.SUM
                                , new ScriptObj("return Long.parseLong(doc['requestSize.keyword'].value)"), new LongValueParser()))
                        .addAggs(new DefaultAggsQuery("averageTimeDelay", AggsEnums.SUM
                                , new FieldObj("latencies.request"))))
                .build();
        String queryString = JsonUtils.toJsonString(build);
        System.out.println(queryString);
        System.out.println("---------------------");

        // 获取查询的索引，并拼接成查询地址
        String esIndex = "service_center_instance_log-2021.03.23/_search";
        HttpUtil.ResonseEntity resonseEntity = HttpUtil.doPostRequest(esUrl + esIndex, queryString);
        String responseBody = resonseEntity.getResponseBody();

        System.out.println(resonseEntity.getCode());
        System.out.println(responseBody);
        System.out.println("---------------------");

        // 解析结果
        List<ValueReceiver> list = (List<ValueReceiver>) build.parse(responseBody, EsDataResult4Service::new);
        System.out.println(list);
        System.out.println("---------------------");
    }
}
